/* $RCSFile: NOkFromPaypal.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/EndTransac/NOkFromPaypal.aspx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:11  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Configuration;
using AddonNice.ECommerce;
using AddonNice.Settings.ECommerce;
using AddonNice.ECommerce.UI;
using AddonNice.ECommerce.Gateways.Payment;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.EndTransac
{
	/// <summary>
	/// Summary description for NOkFromPaypal.
	/// </summary>
	public partial class NOkFromPaypal : EndTransacPage
	{
        /// <summary>
        /// Reserved Page used here to have endtransac pages share same theme
        /// </summary>
        public override int PageID
        {
            get
            {
                return StStr.PageECommerceEndTransac;
            }
        }

        // Paypal send the user back to our site after a transaction finished succesfully, 
		// this does not mean that the payment is accepted
		// Information to be specified by Atos
		protected void Page_Load(object sender, System.EventArgs e)
		{
			//We want to avoid using back button of browser....
			Response.Cache.SetCacheability(HttpCacheability.NoCache);

			if (IPNTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NokFromPayPal Page_Load date : {0}",DateTime.UtcNow),IPNTraceSwitch.Sw.Info);

			if (!IsPostBack)
			{
				string	RawTransac			=	Request.Form.ToString();
				object	obj					=	Request.Form["custom"];
				// Extract TransactionID, OrderID, MerchandID and save raw ipn
				if ( obj == null )
				{
					if (IPNTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]NokFromPayPal Page_Load Err obj == null date: {0}, RawTransac: [{1}]",DateTime.UtcNow,RawTransac),IPNTraceSwitch.Sw.Info);
					return;
				}
				string	custom				=	(string)obj;
				string[] CodeStr			=	PaymentGtwBase.DecodeMark(custom);
				int TransacID				=	int.Parse(CodeStr[0]);
				Guid MerchantID				=	new Guid(CodeStr[1]);
				Guid OrderID			    =	new Guid(CodeStr[2]);
				Guid UserID					=	new Guid(CodeStr[3]);
				string	Key2Ckeck			=	CodeStr[4];
				DateTime TransacDate		=	DateTime.UtcNow;
				try
				{
					new PaymentsDB().InsertReceivedIPN(TransacID,OrderID,MerchantID,TransacDate,RawTransac);
				}
				catch(Exception ex)
				{
					if (IPNTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]NokFromPayPal Page_Load Err Inserting Transac ex: {0}, RawTransac :[{1}]",ex.Message,RawTransac),IPNTraceSwitch.Sw.Info);
				}

				if (IPNTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]NokFromPayPal Page_Load GetGatewayWithData date: {0}, MerchantID: {1}",DateTime.UtcNow,MerchantID),IPNTraceSwitch.Sw.Info);

				PaymentGtwBase gateway			=	new PaymentGtwManager().GetGatewayWithData("Paypal", MerchantID);									
				gateway.InitFromResponse(Request.Form,custom);

				if (IPNTraceSwitch.Sw.TraceInfo)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"NokFromPayPal Page_Load FinalizeOrder(false) date: {0}",DateTime.UtcNow),IPNTraceSwitch.Sw.Info);

				// Call FinalizeOrder control for sending emails and showing receipt
				FinalizeOrder1.ProcessCheckOut(gateway,false);
			}
		}

        /// <summary>
        /// Redirect user back to the Portal Home Page
        /// </summary>
        void ContinueBtn_Click(object sender, ImageClickEventArgs e)
        {
			AddonNice.Security.PortalSecurity.PortalHome(true,this);
		}

        
        #region Std overrides

        ImageButton ContinueBtn =   null;

        protected override void OnPreInit(EventArgs e)
        {
            MasterPage m                =   Master; // to instanciate all controls Cf bug asp.ent
            string strcult              =   LocalizeHelper.GetCurrentNeutralCultureName();
            ContinueBtn                 =   new ImageButton();
            ContinueBtn.ID              =   "BtnContinue";
            ContinueBtn.SkinID          =   "next_" + strcult;
            PlaceHolderButtons.Controls.Add(ContinueBtn);
            base.OnPreInit(e);
        }


		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{
            Load                +=  new EventHandler(Page_Load);
            ContinueBtn.Click   +=  new ImageClickEventHandler(ContinueBtn_Click);
		}

        #endregion Std overrides
	}
}
